package com.lanou.myim.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;

import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.lanou.myim.R;

import com.lanou.myim.entity.EventBusConstant;
import com.lanou.myim.entity.MsgEty;

import com.lanou.myim.presenter.MainPresenter;
import com.lanou.myim.presenter.MainPresenterInterface;

import com.lanou.myim.ui.fragment.ConversationFragment;
import com.lanou.myim.ui.fragment.DiscoveryFragment;
import com.lanou.myim.ui.fragment.FriendsFragment;
import com.lanou.myim.ui.fragment.PersonalFragment;


import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class MainActivity extends BaseActivity implements MainActivityInterface{
    private TabHost tabHost;
    private TextView unReadCountTv;
    private ImageView friendInformIV;
    private MainPresenterInterface mainPresenter;
    private NewMessageBroadcastReceiver msgReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {



        //1111111111111111111111111111111111111111111111
        //222222222222222222222222222222222222222222222
        //333333333333
        //555555555555555
        //我李四最牛逼
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        View conversationTabView = getLayoutInflater().inflate(R.layout.tab_conversation,null);
        View friendTabView = getLayoutInflater().inflate(R.layout.tab_friends,null);
        View discoveryTabView = getLayoutInflater().inflate(R.layout.tab_discovery,null);
        View personalTabView = getLayoutInflater().inflate(R.layout.tab_personal,null);

        unReadCountTv = (TextView) conversationTabView.findViewById(R.id.tv_unread_count);
        friendInformIV = (ImageView) friendTabView.findViewById(R.id.iv_main_friend_inform);



        


        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("tab_conversation")
                .setIndicator(conversationTabView)
                .setContent(R.id.tab_conversation));
        tabHost.addTab(tabHost.newTabSpec("tab_friends")
                .setIndicator(friendTabView)
                .setContent(R.id.tab_friends));
        tabHost.addTab(tabHost.newTabSpec("tab_discovery")
                .setIndicator(discoveryTabView)
                .setContent(R.id.tab_discovery));
        tabHost.addTab(tabHost.newTabSpec("tab_personal")
                .setIndicator(personalTabView)
                .setContent(R.id.tab_personal));
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        transaction.replace(R.id.tab_conversation,new ConversationFragment());
        transaction.replace(R.id.tab_friends,new FriendsFragment());
        transaction.replace(R.id.tab_discovery, new DiscoveryFragment());
        transaction.replace(R.id.tab_personal, new PersonalFragment());
        transaction.commit();


        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

        mainPresenter = new MainPresenter(this);
        mainPresenter.remindUnreadMsg();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(msgReceiver);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showCount(Integer count) {
        unReadCountTv.setText(count.toString());
        unReadCountTv.setVisibility(View.VISIBLE);
    }

    @Override
    public void dismissCount() {
        unReadCountTv.setVisibility(View.GONE);
    }

    //接收好友状态消息
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMainEvent(Integer i) {
     if (i == EventBusConstant.SHOW_FRIEND_INFORM){
         friendInformIV.setVisibility(View.VISIBLE);
     }else if (i == EventBusConstant.DISMISS_FRIEND_INFORM){
         friendInformIV.setVisibility(View.GONE);
     }else if (i == EventBusConstant.REFRESH_UNREAD_COUNT){
         mainPresenter.remindUnreadMsg();
     }
    }



    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 注销广播
            abortBroadcast();

            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取message对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            // 如果是群聊消息，获取到group id

            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(username)) {
                // 消息不是发给当前会话，return
                return;
            }
            String type = message.getType().toString();
            if (type.equals("TXT")) {
                String content = message.getBody().toString();
                int length = content.length();
                content = content.substring(5, length - 1);
                MsgEty msgEty = new MsgEty(EMChatManager.getInstance().getCurrentUser(), username, content, message.getMsgTime(), 0);
                EventBus.getDefault().post(msgEty);

            }else if (type.equals("IMAGE")){
                MsgEty msgEty = new MsgEty(EMChatManager.getInstance().getCurrentUser(), username,"[图片]", message.getMsgTime(), 0);
                EventBus.getDefault().post(msgEty);
            }else if (type.equals("VOICE")){
                MsgEty msgEty = new MsgEty(EMChatManager.getInstance().getCurrentUser(), username,"[语音]", message.getMsgTime(), 0);
                EventBus.getDefault().post(msgEty);
            }
            EventBus.getDefault().post(message);
            mainPresenter.remindUnreadMsg();
        }
    }

}
